package com.weitu.shiro.listener;

import com.weitu.permission.log.entity.LoginLog;
import com.weitu.permission.log.service.LogService;
import org.apache.shiro.session.Session;
import org.apache.shiro.session.SessionListenerAdapter;
import org.springframework.beans.factory.annotation.Autowired;

/**
 * @author zhangqingxi 2017/3/21
 */
public class UserSessionListener extends SessionListenerAdapter {

    private final LogService logService;

    @Autowired
    public UserSessionListener(LogService logService) {
        this.logService = logService;
    }

    @Override
    public void onStart(Session session) {
        System.out.println("初始化sessionId:"+session.getId());
        super.onStart(session);
    }

    @Override
    public void onStop(Session session) {

        updateLoginLogById(session);
        super.onStop(session);
    }

    @Override
    public void onExpiration(Session session) {
        updateLoginLogById(session);
        super.onExpiration(session);

    }

    private void updateLoginLogById(Session session){
        //获得session 中 登录日志ID
        String loginLogId=session.getAttribute("loginLogId").toString();

        LoginLog loginLog=new LoginLog();

        loginLog.setId(loginLogId);

        logService.updateLoginLogById(loginLog);

        System.out.println("session 失效 登录日志ID:"+loginLogId);
    }
}
